<template>
	<view style="width: 100%;">
		<u-cell-item @click="show = true" :title="label || placeholder"></u-cell-item>
		<u-picker
			v-model="show"
			@confirm="selected"
			:mode="mode"
			:params="params"
			:range="range"
			:range-key="rangeKey"
			:rangeValue="rangeValue"
			:default-time="defaultTime"
			:default-selector="defaultSelector"
		></u-picker>
	</view>
</template>

<script>
export default {
	model: {
		prop: 'value',
		event: 'input'
	},
	props: {
		value: {
			type: String,
			default: function() {
				return '';
			}
		},
		placeholder: {
			type: String,
			default: function() {
				return '请选择';
			}
		},
		mode: {
			type: String,
			default: function() {
				return 'selector';
			}
		},
		params: {
			type: Object,
			default: function() {
				return {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false,
					province: true,
					city: true,
					area: true,
					timestamp: true
				};
			}
		},
		range: {
			type: Array,
			default: function() {
				return [];
			}
		},
		rangeKey: {
			type: String,
			default: function() {
				return 'dictValue';
			}
		},
		rangeValue: {
			type: String,
			default: function() {
				return 'dictCode';
			}
		}
	},
	mounted: function() {
		if (this.value) {
			if (this.mode == 'time') {
				this.defaultTime = this.value || '';
				this.label = this.value || '';
			} else if (this.mode == 'selector') {
				for(let i in this.range) {
					if (this.range[i][this.rangeValue] == this.value) {
						this.defaultSelector = [Number(i)];
						this.label =this.range[i][this.rangeKey];
					}
				}
			}
		}
	},
	data() {
		return {
			show: false,
			defaultTime: '', // 黙认时间
			defaultSelector: [], // 黙认选项索引
			label: '' // 显示字符串
		};
	},
	methods: {
		// 选择项
		selected: function(e) {
			let value = '';
			let label = '';
			if (this.mode == 'time') {
				if (e.hour) {
					value = [e.year, e.month, e.day].join('-') + ' ' + [e.hour, e.minute, e.second].join(':');
				} else {
					value = [e.year, e.month, e.day].join('-');
				}
				label = value;
			} else if (this.mode == 'selector') {
				value = this.range[e[0]][this.rangeValue] || '';
				label = this.range[e[0]][this.rangeKey] || '';
			}
			this.label = label;
			this.$emit('input', value);
			this.show = false;
		}
	}
};
</script>

<style lang="scss" scoped></style>
